package com.neu.canteen.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.neu.canteen.dao.FoodTypeDao;
import com.neu.canteen.domain.FoodType;
import com.neu.canteen.utils.JdbcUtil;

public class FoodTypeDaoImpl implements FoodTypeDao{

	@Override
	public List<FoodType> findAll() {
		
		List<FoodType> foodTypes = new ArrayList<FoodType>();
		
		Connection conn = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			conn = JdbcUtil.getConn();
			
			preparedStatement =  conn.prepareStatement("select *from food_type");
			
			resultSet = preparedStatement.executeQuery();

			FoodType foodType = null;
			while(resultSet.next()){
				
				foodType = new FoodType();
				
				foodType.setId(resultSet.getInt("id"));
				foodType.setName(resultSet.getString("name"));
				foodType.setIcon(resultSet.getString("icon"));
				foodTypes.add(foodType);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.close(resultSet,preparedStatement,conn);
		}
		return foodTypes;
	}
	
	public int add(FoodType foodType){
		Connection conn=null;
		PreparedStatement preparedStatement=null;
		try {
			conn=JdbcUtil.getConn();
			String sql="insert into food_type(name,icon) value (?,?)";
			preparedStatement=conn.prepareStatement(sql);
			preparedStatement.setString(1,foodType.getName());
			preparedStatement.setString(2,foodType.getIcon());
	
			return preparedStatement.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			JdbcUtil.close(null, preparedStatement, conn);
		}
		return -1;
	}
	
	@Override
	public int deleteFoodTypeId(int id) {
		 
		Connection conn =null;
		PreparedStatement preparedStatement=null;
		try {
			conn = JdbcUtil.getConn();
			
			String sql = "delete from food_type where id = ?";
			preparedStatement = conn.prepareStatement(sql);
			
			preparedStatement.setInt(1, id);
			return preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.close(null, preparedStatement, conn);
		}
		return -1;
	}
	
	
	
	public int updataFoodtype(FoodType foodType){
		Connection connection=null;
		PreparedStatement preparedStatement=null;
		try {
			connection=JdbcUtil.getConn();
			String sql=("UPDATE food_type SET name=?,icon=? WHERE id=?" );
			preparedStatement=connection.prepareStatement(sql);
			preparedStatement.setString(1, foodType.getName());
			preparedStatement.setString(2, foodType.getIcon());
			preparedStatement.setInt(3, foodType.getId());
			return preparedStatement.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			JdbcUtil.close(null, preparedStatement, connection);
		}
		return -1;
		
	}
}